#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

#define CMD_SIZE 64
#define CMD_STR_SIZE 32

int main()
{
    char cmd[CMD_SIZE] = {0};          // 用户输入的cmd
    char *cmd_str[CMD_STR_SIZE] = {0}; // 存放解析后的cmd 字符串数组
    char *other = NULL;
    int ret = 0;

    for (;;)
    {
        printf("minishell > ");
        fflush(stdout);
        fgets(cmd, sizeof(cmd), stdin);

        cmd[strlen(cmd) - 1] = '\0';
        if (strncmp(cmd, "quit", 4) == 0)
        {
            printf("Bye.\n");
            break;
        }

        // 解析cmd,以" "分割存入cmd_str
        int index = 0;
        cmd_str[index++] = strtok(cmd, " ");
        while ((other = strtok(NULL, " ")) != NULL)
        {
            cmd_str[index++] = other;
        }
        cmd_str[index] = NULL; // cmd_str最后一个参数一定是NULL结尾

        pid_t cpid;

        // 创建子进程
        cpid = fork();
        if (cpid == -1)
        {
            perror("[ERROR] fork(): ");
            exit(EXIT_FAILURE);
        }
        else if (cpid == 0)
        {
            ret = execvp(cmd_str[0], cmd_str);
            if (ret == -1)
            {
                perror("[ERROR] execvp(): ");
                exit(EXIT_FAILURE);
            }
        }
        else if (cpid > 0)
        {
            waitpid(cpid, NULL, 0); // 阻塞等待
        }
    }

    return 0;
}
